#include <iostream>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"
using namespace my_log;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Usage " << argv[0] << " ip port";
        exit(USAGE_ERRO);
    }
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        LOG(Level::FATAL) << "client socket fial";
        exit(SOCKET_ERRO);
    }
    InetAddr addr(std::stoi(argv[2]), argv[1]);
    // 申请服务
    int n = connect(socketfd, addr.getaddr(), addr.getlen());
    if (n < 0)
    {
        LOG(Level::FATAL) << "connect fail";
        exit(CONNECT_ERRO);
    }
    LOG(Level::INFO) << "connect success";
    while (true)
    {
        cout << "Please Enter# ";
        string message;
        getline(std::cin, message);
        write(socketfd, message.c_str(), message.size());
        char buffer[1024];
        int n = read(socketfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = '\0';
            cout<<"Server say# "<<message<<endl;
        }
        close(socketfd);
    }
    return 0;
}